package com.clarence.dada.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.clarence.dada.core.enums.DbFieldEnum;
import com.clarence.dada.core.enums.YesOrNotEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义myBatis-Plus自动填充类
 *
 * @author GD
 * @since 2020-07-30 10:25
 */
@Component
@Slf4j
public class FillMetaObjHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
//        if (!LoginContextHolder.getContext().hasLogin()) {
//            return;
//        }
//        LoginUser currentUser = LoginContextHolder.getContext().getUser();
//        setValue(metaObject, "updateUser", currentUser.getId());

        boolean createUserIs = metaObject.hasSetter(DbFieldEnum.CREATE_USER.getValue());
        boolean createTimeIs = metaObject.hasSetter(DbFieldEnum.CREATE_TIME.getValue());
        if (createUserIs) {
            setFieldValByName(DbFieldEnum.CREATE_USER.getValue(), -1L, metaObject);
        }
        if (createTimeIs) {
            setFieldValByName(DbFieldEnum.CREATE_TIME.getValue(), LocalDateTime.now(), metaObject);
        }

        boolean delFlagIs = metaObject.hasSetter(DbFieldEnum.DEL_FLAG.getValue());
        if (delFlagIs) {
            setFieldValByName(DbFieldEnum.DEL_FLAG.getValue(), YesOrNotEnum.N.getCode(), metaObject);
        }

        boolean updateUserIs = metaObject.hasSetter(DbFieldEnum.UPDATE_USER.getValue());
        boolean updateTimeIs = metaObject.hasSetter(DbFieldEnum.UPDATE_TIME.getValue());
        if (updateUserIs) {
            setFieldValByName(DbFieldEnum.UPDATE_USER.getValue(), -1L, metaObject);
        }
        if (updateTimeIs) {
            setFieldValByName(DbFieldEnum.UPDATE_TIME.getValue(), LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        if (!LoginContextHolder.getContext().hasLogin()) {
//            return;
//        }
//        LoginUser currentUser = LoginContextHolder.getContext().getUser();
//        setValue(metaObject, "updateUser", currentUser.getId());

        boolean updateUserIs = metaObject.hasSetter(DbFieldEnum.UPDATE_USER.getValue());
        boolean updateTimeIs = metaObject.hasSetter(DbFieldEnum.UPDATE_TIME.getValue());
        if (updateUserIs) {
            setFieldValByName(DbFieldEnum.UPDATE_USER.getValue(), -1L, metaObject);
        }
        if (updateTimeIs) {
            setFieldValByName(DbFieldEnum.UPDATE_TIME.getValue(), LocalDateTime.now(), metaObject);
        }
    }

}
